package com.keta.generate;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.keta.generate.db.Table;
import com.keta.generate.util.JdbcPool;

/**
 * 数据库表信息工具
 * 
 * @author 00fly
 * @version [版本号, 2018-11-14]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class MyDataSource
{
    /**
     * 获取指定表的表结构
     * 
     * @param tableName
     * @return
     * @throws SQLException
     * @see [类、类#方法、类#成员]
     */
    public abstract Table getTable(String tableName)
        throws SQLException;
    
    /**
     * 查询该数据库下全部表名
     * 
     * @return
     * @throws SQLException
     * @see [类、类#方法、类#成员]
     */
    public abstract Set<String> getAllTableName()
        throws SQLException;
    
    /**
     * 获取全部表结构
     * 
     * @return
     * @throws SQLException
     * @see [类、类#方法、类#成员]
     */
    public List<Table> getTables()
        throws SQLException
    {
        Set<String> tables = getAllTableName();
        List<Table> list = new ArrayList<>();
        for (String table : tables)
        {
            list.add(getTable(table));
        }
        return list;
    }
    
    /**
     * 查询数据库表字段名
     * 
     * @param tableName
     * @return
     * @throws SQLException
     * @see [类、类#方法、类#成员]
     */
    public List<String> queryColumnNames(String tableName)
        throws SQLException
    {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try (Connection connection = getConnection())
        {
            List<String> columnNames = new ArrayList<>();
            String sql = String.format("select * from %s", tableName);
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            for (int i = 1; i <= columnCount; i++)
            {
                columnNames.add(md.getColumnName(i));
            }
            return columnNames;
        }
        finally
        {
            close(rs);
            close(ps);
        }
    }
    
    protected Connection getConnection()
        throws SQLException
    {
        return JdbcPool.getConnection();
    }
    
    protected static void close(Connection connection)
    {
        JdbcPool.close(connection);
    }
    
    protected static void close(ResultSet rs)
    {
        JdbcPool.close(rs);
    }
    
    protected static void close(PreparedStatement ps)
    {
        JdbcPool.close(ps);
    }
    
    public static void close(Statement stmt)
    {
        JdbcPool.close(stmt);
    }
}
